package com.yzd.learnjava.io;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

import com.yzd.learnjava.util.Print;

public class LockMappedFiles {
	static final int LENGTH = 0x8FF;
	static FileChannel channel;
	public static void main(String[] args) throws IOException {
		channel = new RandomAccessFile("test.dat", "rw").getChannel();
		MappedByteBuffer out = channel.map(FileChannel.MapMode.READ_WRITE, 0, LENGTH);
		for(int i = 0 ; i < LENGTH; i++) {
			out.put((byte)'X');
		}
		
		new LockAndModify(out, 0, 0 + LENGTH / 3);
		new LockAndModify(out, LENGTH / 2 , LENGTH / 2 + LENGTH / 4);
	}
	
	private static class LockAndModify extends Thread{
		private ByteBuffer buff ;
		private int start;
		private int end;
		
		LockAndModify(ByteBuffer bb, int start, int end){
			this.start = start;
			this.end = end;
			bb.limit(end);
			bb.position(start);
			buff = bb.slice();
			start();
		}
		
		@Override
		public void run() {
			try {
				FileLock lock = channel.lock(start, end, false);
				Print.print("Locked , start " + start + " to " + end);
				while(buff.position() < buff.limit() - 1) {
					buff.put((byte)(buff.get() + 1));
				}
				lock.release();
				Print.print("Release , start " + start + " to " + end);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
